package com.jade.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Method;
import java.util.Map;

@Component
@RequestMapping("/common")
public class CallServiceController {
	private static final Logger log = LoggerFactory
			.getLogger(CallServiceController.class);


	@Autowired
	private ApplicationContext applicationContext;

	@Value("${commom.isCloud}")
	private String isCloud;
	/**
	 * 接入cloud的时候，需要
	 * @param map
	 * @return
	 */
	@PostMapping("/callService")
	@ResponseBody
	public CommonResponse callService(@RequestBody Map<String,Object> map) {
		
			return localCall(map);
	}


	/**
	 * 本地调用，返回最后调用结果，第一个参数是接口的声明注解，第二个参数是参数对象
	 * @param annotation 
	 * 
	 * @param parseObject
	 * @param jsonParam
	 * @return
	 */
	private CommonResponse localCall(Map<String, Object> paramMap) {
		Object invoke = "";
		String serverName ="";
		String methodName ;
		Method[] methods;
		Object bean;
		try {
			serverName = paramMap.get("serverName")+"";
		    methodName = paramMap.get("methodName")+"";
			
			if (paramMap==null||StringUtils.equals("NULL", serverName)||StringUtils.equals("NULL", methodName)) {
				return CommonResponse.failResponse("接口声明错误，请联系对应接口人");
			}
			log.info("调用服务请求" +serverName+"/"+methodName );
			Class<?> Classes = applicationContext.getBean(serverName).getClass();
			methods = Classes.getMethods();
			bean = applicationContext.getBean(Classes);
		} catch (Exception e1) {
			e1.printStackTrace();
			log.error("调用本地方法失败：url=" + serverName);
			return CommonResponse.failResponse("方法名调用错误");
		}
		for (Method method : methods) {
			try {
				String name = method.getName();
				System.out.println("当前方法名为" + name + "目标方法名为" + methodName);
				if (StringUtils.equals(methodName, name)) {
					invoke = method.invoke(bean, paramMap.get("paramMap"));
					return CommonResponse.successResponse(invoke);
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("调用本地方法失败：url=" + serverName);
				return CommonResponse.failResponse(e.getMessage());
			}
		}
		return CommonResponse.failResponse("未找到指定方法");
	}

}
